import React, { useState, useEffect, useCallback } from "react";
import {
  View,
  Text,
  TouchableOpacity,
  Dimensions,
  Modal as RNModal,
  TouchableWithoutFeedback,
  SafeAreaView,
} from "react-native";
import { useTheme } from "@/contexts/ThemeContext";
import { styles } from "./index.style";
import { Ionicons } from "@expo/vector-icons";
import { Avatar } from "@rneui/themed";
import GroupMembersList from "../components/MemberList";
import FriendsStateStore from "@/store/friend";
import { getFriendList } from "@/services/api/friend";
import {
  GroupMember,
  InviteMembersModalProps,
  GroupMembersListMode,
} from "@/types/group-chat";

const mockGroupMembers = ["f1", "f3"]; // 假设f1和f3已经是群成员

// 获取好友数据
const loadFriendsData = async () => {
  try {
    const resp = await getFriendList();
    if (resp.data.code === 200) {
      return resp.data.data.map((f) => ({
        ...f,
        avatar: f.avatar || "https://randomuser.me/api/portraits/men/32.jpg",
      }));
    }
    return [];
  } catch (error) {
    console.error("加载好友数据失败:", error);
    return [];
  }
};

const InviteMembersModal: React.FC<InviteMembersModalProps> = ({
  visible,
  onClose,
  groupId = "",
  groupName = "",
  groupAvatar = "",
  groupMembers = mockGroupMembers,
  onInvite,
}) => {
  const { colors } = useTheme();
  const [selectedFriends, setSelectedFriends] = useState<string[]>([]);

  // 直接从store获取状态，避免使用hook
  const [friends, setFriends] = useState<GroupMember[]>([]);
  const [loading, setLoading] = useState(false);

  // 获取好友数据
  const loadFriends = useCallback(async () => {
    const { friends, loading } = FriendsStateStore.getState().state;

    setFriends(friends || []);
    setLoading(loading);

    if (!friends || friends.length === 0) {
      setLoading(true);
      try {
        const updatedFriends = await loadFriendsData();
        setFriends(updatedFriends || []);
        setLoading(false);
      } catch (error) {
        console.error("加载好友数据失败:", error);
        setLoading(false);
      }
    }
  }, []);

  // 优化的数据加载逻辑
  useEffect(() => {
    if (visible) {
      loadFriends();
    }

    // 关闭时重置选择状态
    return () => {
      if (!visible) {
        setSelectedFriends([]);
      }
    };
  }, [visible, loadFriends]);
  const handleSelectFriend = useCallback((friendId: string) => {
    setSelectedFriends((prev) => {
      if (prev.includes(friendId)) {
        return prev.filter((id) => id !== friendId);
      } else {
        return [...prev, friendId];
      }
    });
  }, []);
  const handleInvite = useCallback(() => {
    if (selectedFriends.length === 0) return;

    if (onInvite) {
      onInvite(selectedFriends);
    }

    // 重置状态并关闭模态框
    setSelectedFriends([]);
    onClose();
  }, [selectedFriends, onInvite, onClose]);

  return (
    <RNModal
      visible={visible}
      transparent={true}
      animationType="slide"
      onRequestClose={onClose}
      statusBarTranslucent={true}
    >
      <SafeAreaView style={styles.modalContainer}>
        <TouchableWithoutFeedback onPress={onClose}>
          <View style={styles.backdrop} />
        </TouchableWithoutFeedback>

        <View style={styles.modalContent}>
          {/* 标题栏 */}
          <View style={styles.header}>
            <TouchableOpacity onPress={onClose} style={styles.closeButton}>
              <Ionicons name="close" size={24} color={colors.text.primary} />
            </TouchableOpacity>

            <Text style={[styles.title, { color: colors.text.primary }]}>
              邀请好友加入群聊
            </Text>

            <TouchableOpacity
              onPress={handleInvite}
              style={[
                styles.inviteButton,
                selectedFriends.length === 0 && styles.disabledButton,
              ]}
              disabled={selectedFriends.length === 0}
            >
              <Text
                style={[
                  styles.inviteButtonText,
                  selectedFriends.length === 0 && styles.disabledButtonText,
                ]}
              >
                邀请
              </Text>
            </TouchableOpacity>
          </View>

          {/* 群聊信息 */}
          {groupName && (
            <View style={styles.groupInfo}>
              <Avatar
                rounded
                size={50}
                source={{
                  uri:
                    groupAvatar ||
                    "https://randomuser.me/api/portraits/men/32.jpg",
                }}
                containerStyle={styles.groupAvatar}
              />

              <View style={styles.groupTextInfo}>
                <Text
                  style={[styles.groupName, { color: colors.text.primary }]}
                >
                  {groupName}
                </Text>

                <Text
                  style={[
                    styles.groupMemberCount,
                    { color: colors.text.secondary },
                  ]}
                >
                  邀请好友加入群聊
                </Text>
              </View>
            </View>
          )}

          {/* 已选择计数 */}
          {selectedFriends.length > 0 && (
            <View style={styles.selectedCount}>
              <Text
                style={[
                  styles.selectedCountText,
                  { color: colors.text.secondary },
                ]}
              >
                已选择 {selectedFriends.length} 位好友
              </Text>
            </View>
          )}

          {/* 好友列表 */}
          <View style={styles.listContainer}>
            <GroupMembersList
              mode={GroupMembersListMode.INVITE}
              friends={friends}
              loading={loading}
              selectedIds={selectedFriends}
              onSelectItem={handleSelectFriend}
              groupMembers={groupMembers}
            />
          </View>
        </View>
      </SafeAreaView>
    </RNModal>
  );
};

export default InviteMembersModal;
